# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import codecs
import json
from jobs.models import DBSession, JobModel, create_table


# 写入JSON文件
class JobsPipeline(object):
    def open_spider(self, spider):
        self.file = codecs.open("a51jobs.json", "w", "utf-8")

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        return item

    def close_spider(self, spider):
        self.file.close()


# 写入MySQL
class MySQLPipeline(object):
    def __init__(self):
        create_table()
        self.session = DBSession()

    def open_spider(self, spider):
        print('Spider Opened')

    def insert(self, item):
        if item:
            model = JobModel(
                job=item['job'],
                job_link=item['job_link'],
                company=item['company'],
                company_link=item['company_link'],
                location=item['location'],
                salary=item['salary'],
                time=item['time']
            )
            self.session.add(model)
            self.session.commit()

    def process_item(self, item, spider):
        self.insert(item)
        return item

    def close_spider(self, spider):
        self.session.close()


# 写入mongodb
class MongoPipeline(object):
    def open_spider(self, spider):
        pass

    def process_item(self, item, spider):
        pass

    def close_spider(self, spider):
        pass
